import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Spin, Empty, Tooltip, Button, Tabs, Modal, Select, message, Pagination } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { PrimaryC, DATA_ENTRY, AdvancedSearch, ModalC, TableC, FirstHeaderC, ContentPackage } from '../../../comps';
import WorkModalC from './workModal';
import myStyle from './index.less';
import { getUserInfo } from '../../../utils/commonFunc';

const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const { TabPane } = Tabs;
const { confirm } = Modal;
const { Option } = Select;
const FormItemLayout = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 9, offset: 0 },
    xxl: { span: 8, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 13, offset: 0 },
    xxl: { span: 14, offset: 0 },
  },
};
const FormItemLayout1 = {
  labelCol: {
    xs: { span: 4, offset: 0 },
    sm: { span: 8, offset: 0 },
    md: { span: 8, offset: 0 },
    lg: { span: 8, offset: 0 },
    xl: { span: 7, offset: 0 },
    xxl: { span: 6, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 18, offset: 0 },
    sm: { span: 14, offset: 0 },
    md: { span: 14, offset: 0 },
    lg: { span: 14, offset: 0 },
    xl: { span: 13, offset: 0 },
    xxl: { span: 14, offset: 0 },
  },
};
//设置默认流程模板
const flowNumberList = [{ value: '1', title: '默认模板' }];
@connect(({ workFlowM, globalM, loading }) => ({
  workFlowM,
  globalM,
  loading,
}))
@Form.create()
export default class WorkFlow extends PureComponent {
  state = {
    visibleModal: false, //模态框显示与否
    modalData: {}, //详情页数据
    currentPage: 1, //当前页码
    numInPage: 10, //每页数量
    isReset: false, //是否点击重置按钮
    flowListSearch: {}, //工作流查询条件
  };

  componentDidMount() {
    this.queryTableList();
  }
  componentWillUnmount() {
    //离开前清除models数据
    this.props.dispatch({
      type: 'workFlowM/setState',
      payload: {
        columns: undefined, //工作流查询列表表头
        dataSource: undefined, //工作流查询列表数据源
        pageInfo: {}, //工作流列表信息
      },
    });
  }
  //判断是否是管理员
  isAdmin = () => {
    let temp = getUserInfo().isTenantAdmin;
    return temp;
  };
  showValue = (value, arr) => {
    if (!arr.length) return value || '--';
    let text = '';
    arr.forEach((item) => {
      if (item.code === value) text = item.value;
    });
    return text || '--';
  };
  showValue1 = (value, arr) => {
    if (!arr.length) return value || '--';
    let text = '';
    arr.forEach((item) => {
      if (item.value === value) text = item.title;
    });
    return text || '--';
  };
  //查询表格数据
  queryTableList = () => {
    const { dispatch } = this.props;
    const { flowListSearch, isReset, numInPage, currentPage } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    dispatch({
      //查询之前清空数据
      type: 'workFlowM/setState',
      payload: {
        columns: undefined, //工作流查询列表表头
        dataSource: undefined, //工作流查询列表数据源
        pageInfo: {}, //工作流列表信息
      },
    });

    dispatch({
      type: 'workFlowM/queryFlowList',
      payload: {
        ...flowListSearch,
        currentPage,
        numInPage,
      },
    });
  };
  //表格页码排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.queryTableList();
      },
    );
  };
  //删除工作流
  deleteFlow = (e) => {
    this.props.dispatch({
      type: 'workFlowM/deleteFlowById',
      payload: {
        flowNo: e.flowNo,
      },
      callback: (msg) => {
        if (msg == 'success') {
          this.queryTableList(); //删除成功重新查询列表
        }
      },
    });
  };

  //展示表格
  showTable = () => {
    const {
      loading,
      workFlowM: { columns, dataSource, pageInfo },
    } = this.props;
    const { currentPage, numInPage } = this.state;
    const {
      globalM: {
        dataDictionary: { flow = [] },
      },
    } = this.props;
    if (this.isAdmin() && columns && columns.length && columns[columns.length - 1]['key'] != 'operate') {
      const operate = {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        operates: [
          {
            title: '查看',
            onClick: (record, index) => {
              this.openModal('query', record);
            },
          },
          {
            title: '修改',
            onClick: (record, index) => {
              this.openModal('edit', record);
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.deleteFlow(record);
            },
          },
        ],
      };
      columns.push(operate);
    }
    columns &&
      columns.map((item) => {
        if (item.key == 'flowType') {
          item.render = (text, record) => {
            return this.showValue(text, flow);
          };
        }
        if (item.key == 'flowNumber') {
          item.render = (text, record) => {
            return this.showValue1(text, flowNumberList);
          };
        }
      });

    return (
      <div>
        {/* <Spin spinning={loading.effects['workFlowM/queryWaringList'] == true}> */}
        <TableC
          columns={columns}
          dataSource={dataSource}
          onChange={this.handleTableChange}
          current={currentPage}
          total={pageInfo.total || 0}
          pageSize={numInPage}
          rowKey='flowNo'
          selfScrollY={true}
        />
        {/* </Spin> */}
      </div>
    );
  };
  //打开详情弹窗
  openModal = (type, row) => {
    if (type == 'add') {
      this.setState({
        type,
        visibleModal: true,
        modalData: {},
      });
    } else {
      this.setState({
        type,
        visibleModal: true,
        modalData: row,
      });
    }
  };
  render() {
    const { type, modalData, visibleModal } = this.state;
    const {
      globalM: {
        dataDictionary: { flow = [] },
      },
    } = this.props;
    const selectData = [];
    if (!selectData.length) {
      flow.map((item) => {
        selectData.push({
          value: item.code,
          title: item.value,
        });
      });
    }
    const data = [
      {
        dataIndex: 'flowName',
        title: '流程名称',
        type: DATA_ENTRY.INPUT,
        formItemLayout: FormItemLayout1,
      },
      {
        dataIndex: 'flowType',
        title: '业务流程分类',
        type: DATA_ENTRY.SELECT,
        dataSource: selectData,
        isMultiple: true,
        allowClear: true,
        filterOption: false,
        formItemLayout: FormItemLayout,
      },
    ];
    const searchProps = {
      dataSource: data,
      onQuery: (e) => {
        this.setState(
          {
            flowListSearch: e,
            currentPage: 1,
            isReset: false,
          },
          () => {
            this.queryTableList(); //点击查询按钮
          },
        );
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          flowListSearch: {},
          isReset: true,
        });
      },
    };
    return (
      <ContentPackage
        title='工作流管理'
        contentHtml={
          <div>
            <div className='flowMent'>
              <div className='cardBody'>
                <AdvancedSearch {...searchProps} />
              </div>
              {this.isAdmin() && (
                <PrimaryC
                  title='新增'
                  style={{ marginBottom: '10px' }}
                  onClick={() => {
                    this.openModal('add');
                  }}
                />
              )}
              {this.showTable()}
            </div>
            {visibleModal ? (
              <WorkModalC
                modalData={modalData}
                type={type}
                visibleModal={visibleModal}
                triggerVisible={(e) => {
                  this.setState({ visibleModal: e });
                }}
                onQuery={() => {
                  this.queryTableList();
                }}
                flowNumberList={flowNumberList}
              />
            ) : null}
          </div>
        }
      />
    );
  }
}
